package cn.sy.controller;

import cn.sy.dto.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.Response;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

@RestController
@Slf4j
public class WifiController {

	/**
	 * 控制文件保存目录
	 */
	@Value("${sy.uploaddir}")
	private String dir;

	private static final String controllFileName = "shwWifi.txt";

	/*
	 * request:
	 *     http://localhost:8080/
	 */
	@ResponseBody
	@GetMapping("/wifi")
	public ResponseEntity<String> wifiStatus() {
		log.info("WifiController wifiStatus");
		try {
			Path controllFile = Paths.get(dir, controllFileName);
			List<String> lines = Files.readAllLines(controllFile);
			String result = "true";
			if(lines.size() > 0) {
				result = lines.get(0);
			}
			log.info("WifiController wifiStatus: " + result);
			return ResponseEntity.ok(result);
		} catch (Exception e) {
			log.error("WifiController wifiStatus failed.", e);
			throw new RuntimeException(e);
		}
	}

	/*
	 * request:
	 *     http://localhost:8080/
	 */
    @ResponseBody
    @PostMapping("/wifi")
    public ResponseEntity<String> wifi(@RequestParam("action") String action) {
		log.info("WifiController wifi. action=" + action);
		try {
			Path controllFile = Paths.get(dir, controllFileName);
			String content = "false".equals(action) ? "false" : "true";
			Files.write(controllFile, content.getBytes(StandardCharsets.UTF_8));
			log.info("WifiController wifi. " + content);
			return ResponseEntity.ok(content);
		} catch (Exception e) {
			log.error("WifiController wifi. failed.", e);
			throw new RuntimeException(e);
		}
    }
}
